<template>
	<el-card shadow="hover">
		<el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch">
			<el-form-item label="父订单" prop="pay_sn">
				<el-input v-model="queryParams.pay_sn" placeholder="父订单" clearable />
			</el-form-item>
			<el-form-item label="子订单" prop="order_sn">
				<el-input v-model="queryParams.order_sn" placeholder="子订单" clearable />
			</el-form-item>
			<el-form-item label="商品名称" prop="goods_id">
				<el-select
					v-model="queryParams.goods_id"
					filterable
					remote
					clearable
					placeholder="请输入选择商品名称"
					:remote-method="goodsIdRemoteMethod"
					:loading="goodsIdLoading"
					@focus="onGoodsIdFocus"
					@clear="onGoodsIdClear"
				>
					<el-option v-for="item in goodsIdOptions" :key="item.id" :label="item.title" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="买家昵称" prop="user_id">
				<el-select
					v-model="queryParams.user_id"
					filterable
					remote
					clearable
					placeholder="请输入选择用户"
					:remote-method="userIdRemoteMethod"
					:loading="userIdLoading"
					@focus="onUserIdFocus"
					@clear="onUserIdClear"
				>
					<el-option v-for="item in userIdOptions" :key="item.id" :label="item.nickname" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="下单开始时间" prop="create_start_time">
				<el-date-picker v-model="queryParams.create_start_time" type="date" clearable value-format="X" placeholder="请选择开始时间" />
			</el-form-item>
			<el-form-item label="下单结束时间" prop="create_end_time">
				<el-date-picker v-model="queryParams.create_end_time" type="date" clearable value-format="X" placeholder="请选择结束时间" />
			</el-form-item>
			<!-- <el-form-item label="收货地址" prop="area">
				<el-cascader v-model="queryParams.area" :props="shippingAddressProps" placeholder="请选择省市区" clearable />
			</el-form-item>
			<el-form-item label="收货人手机号" prop="order_address_phone">
				<el-input v-model="queryParams.order_address_phone" placeholder="收货人手机号" clearable />
			</el-form-item> -->
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" @click="onQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" @click="onResetQuery">重置</el-button>
			</el-form-item>
		</el-form>
		<el-row :gutter="10" class="top-block mb8">
			<el-col :span="1.5">
				<el-button type="info" plain icon="el-icon-view" :disabled="single" @click="onViewAfterSalesRecord(1)"> 查看售后记录 </el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="info" plain icon="el-icon-view" :disabled="single" @click="onViewAfterSalesRecord(2)"> 查看维权记录 </el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="warning" plain icon="el-icon-download" @click="onExport"> 导出 </el-button>
			</el-col>
			<right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
		</el-row>
		<el-tabs type="border-card" @tab-click="getList" v-model="queryParams.after_sale_type">
			<el-tab-pane label="全部" name="0" />
			<el-tab-pane label="退款" name="1" />
			<el-tab-pane label="退货" name="2" />
			<el-tab-pane label="换货" name="3" />
			<el-tab-pane label="补发" name="4" />
		</el-tabs>
		<el-tabs @tab-click="getList" v-model="queryParams.handle">
			<el-tab-pane name="1">
				<template #label>待处理({{ afterNumber[queryParams.after_sale_type] }})</template>
			</el-tab-pane>
			<el-tab-pane label="处理中" name="2" />
			<el-tab-pane label="已处理" name="3" />
		</el-tabs>
		<el-table :data="tableList" v-loading="loading" @selection-change="onSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="父订单" align="center" prop="pay_sn" />
			<el-table-column label="子订单" align="center" prop="order_sn" />
			<el-table-column label="售后订单" align="center" prop="after_sale_sn" />
			<el-table-column label="商品信息" align="center">
				<template #default="scope">
					<div>{{ scope.row.goods_title }}</div>
					<div>{{ scope.row.goods_options_name }}</div>
				</template>
			</el-table-column>
			<el-table-column label="商品图片" align="center">
				<template #default="scope">
					<img style="width: 60px; height: auto" :src="scope.row.goods_option_icon" />
				</template>
			</el-table-column>
			<el-table-column label="供应商" align="center" prop="supplier_title" />
			<el-table-column label="商品售价" align="center" prop="goods_option_price" />
			<el-table-column label="商品数量" align="center" prop="num" />
			<el-table-column label="支付金额" align="center" prop="real_pay" />
			<el-table-column label="收货人信息" align="center">
				<template #default="scope">
					<div>{{ scope.row.address_name }}</div>
					<div>{{ scope.row.address_mobile }}</div>
					<div>{{ scope.row.address_province + scope.row.address_city + scope.row.address_county }}</div>
					<div>{{ scope.row.address }}</div>
				</template>
			</el-table-column>
			<el-table-column label="买家" align="center" prop="user_nickname" />
			<el-table-column label="买家手机号" align="center" prop="user_mobile" />
			<el-table-column label="下单时间" align="center">
				<template #default="scope">{{ timeDictionary(scope.row.order_create_time) }}</template>
			</el-table-column>
			<el-table-column label="完成时间" align="center">
				<template #default="scope">{{ timeDictionary(scope.row.order_over_time) }}</template>
			</el-table-column>
			<el-table-column label="申请维权时间" align="center">
				<template #default="scope">{{ timeDictionary(scope.row.right_start_time) }}</template>
			</el-table-column>
			<el-table-column label="申请售后人" align="center" prop="apply_user_nickname" />
			<el-table-column label="订单发货物流" align="center">
				<template #default="scope">
					<el-link type="success">{{ scope.row.freight_sn }}</el-link>
				</template>
			</el-table-column>
			<el-table-column label="状态" align="center">
				<template #default="scope">{{ afterSalesOrderStatusText(2, scope.row.after_status) }}</template>
			</el-table-column>
			<el-table-column label="操作">
				<template #default="scope">
					<el-row v-if="Number(queryParams.handle) == 1">
						<el-button type="text" icon="el-icon-edit" @click="onDealWith(scope.row)"> 处理 </el-button>
					</el-row>
					<el-row v-if="Number(queryParams.handle) != 3">
						<el-button type="text" icon="el-icon-edit" @click="onLeaveMessage(scope.row)"> 留言 </el-button>
					</el-row>
					<el-row v-if="Number(queryParams.handle) != 3">
						<el-button type="text" @click="onViewLeaveMessage(scope.row)"> 查看留言 </el-button>
					</el-row>
				</template>
			</el-table-column>
		</el-table>
		<pagination-component
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="getList"
		/>
		<activist-record-dialog ref="activistRecordRef" />
		<after-sales-record-dialog ref="afterSalesRecordRef" />
		<handle-refund-dialog ref="handleRefundRef" />
		<leave-message-dialog ref="leaveMessageRef" />
		<view-leave-message-dialog ref="viewLeaveMessageRef" />
	</el-card>
</template>

<script lang="ts">
import { getCurrentInstance, onMounted, reactive, ref, toRefs } from 'vue';
import { ElLoading } from 'element-plus';
import { getAreaList } from '/@/api/admin';
import { afterRightList, orderSelectGoods, orderSelectUsers, rightNumberSelect, afterRightsListExport } from '/@/api/admin1';
import { afterSalesOrderStatusText, timeDictionary } from '/@/utils/dictionaryTranslation';
import { floatMultiply, floatSub, handleDownloadByName } from '/@/utils/utils';

import ActivistRecordDialog from './dialog/ActivistRecordDialog.vue';
import AfterSalesRecordDialog from './dialog/AfterSalesRecordDialog.vue';
import HandleRefundDialog from './dialog/HandleRefundDialog.vue';
import LeaveMessageDialog from './dialog/LeaveMessageDialog.vue';
import ViewLeaveMessageDialog from './dialog/ViewLeaveMessageDialog.vue';

// 被选择的数据项
let selectionInfo: Array<any> = [];

export default {
	name: 'orderActivist',
	components: { HandleRefundDialog, AfterSalesRecordDialog, ActivistRecordDialog, LeaveMessageDialog, ViewLeaveMessageDialog },
	setup() {
		const { proxy } = getCurrentInstance() as any;
		const state = reactive({
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				after_sale_type: '0',
				handle: '1',
				pay_sn: '',
				order_sn: '',
				goods_id: '',
				user_id: '',
				create_start_time: '',
				create_end_time: '',
				area: [],
				order_address_phone: '',
			},
			goodsIdOptions: [] as any,
			goodsIdLoading: false,
			userIdLoading: false,
			userIdOptions: [] as any,
			shippingAddressProps: {
				checkStrictly: true,
				lazy: true,
				lazyLoad(node: any, resolve: any) {
					const {
						data: { id },
						level,
					} = node;
					_getAreaList({ id: level ? id : 100000 }, level, resolve);
				},
				value: 'name',
				label: 'name',
			},
			afterNumber: [] as any,
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 选中数组
			ids: [],
			showSearch: true,
			tableList: [],
			loading: false,
			total: 20,
		});

		let start_page: number = 1; // 导出售后订单默认页数
		let start_page_total: number = 1; // 导出售后订单总页数
		const queryFormRef = ref(null);
		const activistRecordRef = ref(null);
		const afterSalesRecordRef = ref(null);
		const handleRefundRef = ref(null);
		const leaveMessageRef = ref(null);
		const viewLeaveMessageRef = ref(null);
		const loadingDownloadRef = ref(null);

		onMounted(() => {
			getList();
		});

		/********** 点击事件(on开头) **********/
		// 导出维权
		// 导出
		const onExport = () => {
			(loadingDownloadRef.value as any) = ElLoading.service({
				lock: true,
				text: '正在导出，请耐心等待...',
				background: 'rgba(0, 0, 0, 0.7)',
			});
			_afterRightsListExport(state.queryParams);
		};
		// 选择商品
		const onGoodsIdFocus = () => {
			if (!state.queryParams.goods_id) {
				state.goodsIdLoading = true;
				_orderSelectGoods();
			}
		};
		// 清空商品
		const onGoodsIdClear = () => {
			_orderSelectGoods();
		};
		// 选择买家
		const onUserIdFocus = () => {
			if (!state.queryParams.user_id) {
				state.userIdLoading = true;
				_orderSelectUsers({ type: 0 });
			}
		};
		// 清空买家
		const onUserIdClear = () => {
			_orderSelectUsers({ type: 0 });
		};
		// 搜索
		const onQuery = () => {
			state.queryParams.pageNum = 1;
			getList();
		};
		// 重置
		const onResetQuery = () => {
			(queryFormRef.value as any)?.resetFields();
			onQuery();
		};
		// 查看维权记录
		const onViewAfterSalesRecord = (type: number) => {
			if (type == 1) {
				(afterSalesRecordRef.value as any)?.openDialog({
					data: {
						goods_title: selectionInfo[0].goods_title,
						goods_option_price: selectionInfo[0].goods_option_price,
						cost_price: selectionInfo[0].cost_price,
						num: selectionInfo[0].num,
						returnNum: selectionInfo[0].num,
						sale_id: selectionInfo[0].id,
					},
					title: afterSalesOrderStatusText(2, selectionInfo[0].after_status),
				});
			} else {
				(activistRecordRef.value as any)?.openDialog({
					data: {
						goods_title: selectionInfo[0].goods_title,
						goods_option_price: selectionInfo[0].goods_option_price,
						cost_price: selectionInfo[0].cost_price,
						num: selectionInfo[0].num,
						returnNum: selectionInfo[0].num,
						sale_id: selectionInfo[0].id,
					},
					title: afterSalesOrderStatusText(2, selectionInfo[0].after_status),
				});
			}
		};
		// 添加留言
		const onLeaveMessage = (row: any) => {
			(leaveMessageRef.value as any)?.openDialog(row, () => getList());
		};
		// 查看留言
		const onViewLeaveMessage = (row: any) => {
			(viewLeaveMessageRef.value as any)?.openDialog(row, () => getList());
		};
		// 处理维权
		const onDealWith = (row: any) => {
			(handleRefundRef.value as any)?.openDialog(
				{
					data: {
						goods_title: row.goods_title,
						goods_option_price: row.goods_option_price,
						cost_price: row.cost_price,
						cost_price1: floatSub(floatMultiply(row.cost_price, row.num), row.after_sale_price),
						num: row.num,
						returnNum: row.num,
						refund_status1: 1,
						refund_moeny: floatSub(row.real_pay, row.after_sale_price),
						refund_moeny1: '',
						remark: '',
						sale_id: row.id,
					},
					title: afterSalesOrderStatusText(2, row.after_status),
				},
				() => getList()
			);
		};
		// 多选框选中数据
		const onSelectionChange = (selection: any) => {
			selectionInfo = selection;
			state.single = selection.length !== 1;
			state.multiple = !selection.length;
		};

		/********** 方法事件 **********/
		const getList = () => {
			state.loading = true;
			_rightNumberSelect();
			_afterRightList({
				...state.queryParams,
				order_address_province: state.queryParams.area[0],
				order_address_city: state.queryParams.area[1],
				order_address_county: state.queryParams.area[2],
				create_end_time: state.queryParams.create_start_time
					? state.queryParams.create_end_time
						? Number(state.queryParams.create_end_time) + 86399
						: proxy.dayjs().unix()
					: '',
			});
		};
		// 商品搜索
		const goodsIdRemoteMethod = (query: string) => {
			if (query) {
				state.goodsIdLoading = true;
				_orderSelectGoods({ title: query });
			} else {
				return true;
			}
		};
		//搜索买家
		const userIdRemoteMethod = (query: string) => {
			if (query) {
				state.userIdLoading = true;
				_orderSelectUsers({ nickname: query, type: 0 });
			} else {
				return true;
			}
		};

		/********** 网络事件 **********/
		// 导出维权
		// 导出待发货文件
		const _afterRightsListExport = (_data: any) => {
			if (start_page <= start_page_total) {
				afterRightsListExport(_data)
					.then((res: any) => {
						start_page == 1 && (start_page_total = res.data.info.count_page);
						start_page++;
						handleDownloadByName(res.data.info.url, '维权导出', false);
						_afterRightsListExport(state.queryParams);
						if (start_page >= start_page_total) {
							(loadingDownloadRef.value as any)?.close();
							start_page = 1;
							start_page_total = 1;
						}
					})
					.catch(() => {
						(loadingDownloadRef.value as any)?.close();
						start_page = 1;
						start_page_total = 1;
					});
			}
		};
		// 选择商品（搜索）
		const _orderSelectGoods = (_data: object = {}) => {
			orderSelectGoods(_data)
				.then((res: any) => {
					console.log('选择商品（搜索）', res);
					state.goodsIdOptions = res.data.list;
					state.goodsIdLoading = false;
				})
				.catch(() => {
					state.goodsIdLoading = false;
				});
		};
		// 选择用户(搜索)
		const _orderSelectUsers = (_data: any) => {
			orderSelectUsers(_data)
				.then((res: any) => {
					console.log('选择用户(搜索)', res);
					state.userIdOptions = res.data.list;
					state.userIdLoading = false;
				})
				.catch(() => {
					state.userIdLoading = false;
				});
		};
		// 维权列表
		const _afterRightList = (_data: object) => {
			afterRightList(_data).then((res: any) => {
				console.log('维权列表', res);
				state.tableList = res.data.list;
				state.total = res.data.total;
				state.loading = false;
			});
		};
		// 查询待处理数量-维权
		const _rightNumberSelect = () => {
			rightNumberSelect().then((res: any) => {
				console.log('查询待处理数量-维权', res);
				let number = res.data.info.number1 + res.data.info.number2 + res.data.info.number3 + res.data.info.number4;
				state.afterNumber = [number, res.data.info.number1, res.data.info.number2, res.data.info.number3, res.data.info.number4];
			});
		};
		// 选择省市区
		const _getAreaList = (_data: object, _level: number, resolve: any) => {
			getAreaList(_data).then((res: any) => {
				console.log('选择省市区', res);
				let nodes = res.data.list.map((item: any) => ({
					id: item.id,
					name: item.name,
					leaf: _level >= 2,
				}));
				resolve(nodes);
			});
		};

		return {
			queryFormRef,
			activistRecordRef,
			afterSalesRecordRef,
			handleRefundRef,
			leaveMessageRef,
			viewLeaveMessageRef,
			onGoodsIdFocus,
			onGoodsIdClear,
			onUserIdFocus,
			onUserIdClear,
			onQuery,
			onResetQuery,
			onSelectionChange,
			onViewAfterSalesRecord,
			onDealWith,
			onLeaveMessage,
			onViewLeaveMessage,
			onExport,
			getList,
			goodsIdRemoteMethod,
			userIdRemoteMethod,
			timeDictionary,
			afterSalesOrderStatusText,
			...toRefs(state),
		};
	},
};
</script>

<style lang="scss" scoped></style>
